import 'package:date_format/date_format.dart';
import 'package:dingtalk/core/blocs/message_record/message_record_bloc.dart';
import 'package:dingtalk/core/model/message_item_model.dart';
import 'package:dingtalk/core/utils/common_util.dart';
import 'package:dingtalk/core/values/values.dart';
import 'package:dingtalk/ui/screens/chat/chat_screen.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:nine_grid_view/nine_grid_view.dart';

class THMessageListView extends StatefulWidget {
  @override
  _THMessageListViewState createState() => _THMessageListViewState();
}

class _THMessageListViewState extends State<THMessageListView> {
  @override
  void initState() {
    super.initState();

    _initData();
  }

  _initData() async {
    // await MockChatMessageRecord.initChatMessageRecord();
    BlocProvider.of<THMessageRecordBloc>(context)
      ..add(THMessageRecordListEvent());
  }

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<THMessageRecordBloc, THMessageRecordState>(
        builder: (context, state) {
      if (state is THMessageRecordList) {
        return buildMessageRecordListView(state.recordList);
      }
      return Container();
    });
  }

  ListView buildMessageRecordListView(List<THMessageItemModel> recordList) {
    return ListView.builder(
      itemCount: recordList.isEmpty ? 0 : recordList.length,
      itemBuilder: (BuildContext context, int index) {
        THMessageItemModel model = recordList[index];
        return GestureDetector(
          onTap: () {
            Navigator.push(context,
                MaterialPageRoute(builder: (BuildContext context) {
              return THChatScreen(
                  currentChatUserId: model.userId,
                  currentChatUserName: model.userName);
            }));
          },
          child: Slidable(
            actionPane: SlidableDrawerActionPane(),
            actionExtentRatio: 0.25,
            secondaryActions: <Widget>[
              IconSlideAction(
                caption: '取消置顶',
                color: Colors.black45,
                icon: Icons.more_horiz,
                onTap: () => _showSnackBar('More'),
              ),
              IconSlideAction(
                caption: '删除',
                color: Colors.redAccent,
                icon: Icons.delete,
                onTap: () => _showSnackBar('Delete'),
              ),
            ],
            child: Padding(
              padding:
                  EdgeInsets.only(left: kSize36, bottom: kSize20, top: kSize20),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Expanded(child: THMessageItem(messageModel: model)),
                  model.isStick == 1
                      ? Container(
                          width: kSize48,
                          height: kSize48,
                          margin: EdgeInsets.only(top: kSize10, right: kSize10),
                          child: SvgPicture.asset(
                              'assets/icons/icon_triangle.svg'),
                        )
                      : Padding(
                          padding: EdgeInsets.symmetric(horizontal: kSize24),
                        )
                ],
              ),
            ),
          ),
        );
      },
      shrinkWrap: true,
      physics: NeverScrollableScrollPhysics(),
    );
  }

  _showSnackBar(String desc) {
    print(desc);
  }
}

class THMessageItem extends StatelessWidget {
  final THMessageItemModel messageModel;

  THMessageItem({@required this.messageModel});

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
        THMessageAvatar(messageModel: messageModel),
        Expanded(
          child: Column(
            children: <Widget>[
              Padding(
                padding: EdgeInsets.symmetric(vertical: kSize8),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Expanded(
                      child: Text(
                        messageModel?.chatName ?? "",
                        style: TextStyle(color: kColor33, fontSize: kSize34),
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                    Text(
                      _formatDate(),
                      style: TextStyle(color: kColor99, fontSize: kSize26),
                      overflow: TextOverflow.ellipsis,
                    ),
                  ],
                ),
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  Expanded(
                    child: RichText(
                      text: TextSpan(children: [
                        TextSpan(
                          text: messageModel.isAtYou == 1 ? "[@你]" : "",
                          style:
                              TextStyle(color: kColorF1A33A, fontSize: kSize28),
                        ),
                        TextSpan(
                          text: messageModel.isSpecialAttention == 1
                              ? "[特别关注]"
                              : "",
                          style:
                              TextStyle(color: kColorF1A33A, fontSize: kSize28),
                        ),
                        TextSpan(
                          text: messageModel.isAtAll == 1 ? "[@所有人]" : "",
                          style:
                              TextStyle(color: kColorF1A33A, fontSize: kSize28),
                        ),
                        TextSpan(
                          text: messageModel?.message ?? "",
                          style: TextStyle(color: kColor99, fontSize: kSize28),
                        )
                      ]),
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                  (messageModel.unReadCount != null &&
                          messageModel.unReadCount > 0 &&
                          messageModel.isDisturbing == 0)
                      ? Container(
                          width: kSize32,
                          height: kSize32,
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                              color: kColorE86A3E,
                              borderRadius: BorderRadius.circular(kSize20)),
                          child: Text(
                            "${messageModel.unReadCount}",
                            style: TextStyle(
                                color: Colors.white, fontSize: kSize26),
                          ))
                      : Container(),
                  messageModel.isDisturbing == 1
                      ? Row(
                          children: <Widget>[
                            SvgPicture.asset(
                              'assets/icons/icon_disturbing.svg',
                              width: kSize36,
                              color: kColorECEDED,
                            ),
                            messageModel.unReadCount != null &&
                                    messageModel.unReadCount > 0
                                ? SvgPicture.asset(
                                    'assets/icons/icon_red_dot.svg',
                                    width: kSize36,
                                  )
                                : Container()
                          ],
                        )
                      : Container()
                ],
              )
            ],
          ),
        )
      ],
    );
  }

  String _formatDate() {
    DateTime dateTime =
        DateTime.fromMillisecondsSinceEpoch(messageModel?.time ?? 0);
    return formatDate(dateTime, [HH, ':', nn]) ?? "";
  }
}

class THMessageAvatar extends StatelessWidget {
  final THMessageItemModel messageModel;

  THMessageAvatar({this.messageModel});

  @override
  Widget build(BuildContext context) {
    return messageModel.isSingle == 1
        ? _buildSingleAvatar()
        : _buildGroupAvatar();
  }

  Widget _buildSingleAvatar() {
    return Container(
      margin: EdgeInsets.only(right: kSize24),
      child: (messageModel.isSingle == 1 && messageModel.chatName != null)
          ? CircleAvatar(
              radius: kSize50,
              child: Text(
                geneChatName(messageModel.chatName),
                style: TextStyle(color: Colors.white, fontSize: kSize32),
              ),
              backgroundColor: kPrimaryColor,
            )
          : Image.asset('assets/images/track_icon_attend.png',
              fit: BoxFit.cover),
    );
  }

  Widget _buildGroupAvatar() {
    List<String> groupAvatars = messageModel?.groupAvatars?.split(",") ?? [];
    if (groupAvatars.length >= 4) {
      groupAvatars = groupAvatars?.sublist(0, 4);
    }
    return NineGridView(
      width: kSize100,
      height: kSize100,
      type: NineGridType.dingTalkGp,
      itemCount: groupAvatars?.length,
      space: kSizeDot5,
      margin: EdgeInsets.only(right: kSize24),
      itemBuilder: (BuildContext context, int index) {
        String userName = groupAvatars[index];
        return Container(
          color: kPrimaryColor,

          /// TODO: position ???
          alignment: Alignment.center,
          child: Container(
            margin: EdgeInsets.symmetric(horizontal: kSize6),
            child: Text(
              userName.length >= 2 ? userName.substring(1, 2) : userName,
              style: TextStyle(color: Colors.white),
            ),
          ),
        );
      },
    );
  }
}
